package com.zhw.learning.thread.threadpool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhw
 * 创建一个可定期或者延时执行任务的定长线程池，支持定时及周期性任务执行
 *
 * Executors.newScheduledThreadPool(3):
 * public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
 *         return new ScheduledThreadPoolExecutor(corePoolSize);
 *     }
 * public ScheduledThreadPoolExecutor(int corePoolSize) {
 *         super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
 *               new DelayedWorkQueue());
 *     }
 */
public class ScheduledThreadPoolTest {

    public static void main(String[] args) throws InterruptedException {
        final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

        System.out.println("提交时间: " + sdf.format(new Date()));

        //延迟3秒钟后执行任务
//        scheduledThreadPool.schedule(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("运行时间: " + sdf.format(new Date()));
//            }
//        }, 3, TimeUnit.SECONDS);

        //延迟1秒钟后每隔3秒执行一次任务
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("运行时间: " + sdf.format(new Date()));
            }
        }, 1, 3, TimeUnit.SECONDS);
        Thread.sleep(10000);

        scheduledThreadPool.shutdown();
    }

}
